package com.mall.payment.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.GoodsDetail;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.mall.common.constant.OrderConstant;
import com.mall.common.constant.PaymentConstant;
import com.mall.common.dto.OrderDTO;
import com.mall.common.dto.OrderItemDTO;
import com.mall.payment.entity.PaymentEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 谢君臣
 * @Date: 2022/8/15-18:54
 * @version: 1.0
 * @function:
 */
@Component
@Slf4j
public class PayTemplate {

    @Resource
    private AlipayConfig alipayConfig;
    private final AlipayClient alipayClient;
    public PayTemplate(AlipayClient alipayClient) {
        this.alipayClient = alipayClient;
    }

    public String AliPay(PaymentEntity payment, OrderDTO orders) throws AlipayApiException {
        if (orders==null)
            throw new RuntimeException("支付订单不能为空");
        try {
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            // 通知
            request.setNotifyUrl(alipayConfig.getNotifyUrl());
            // 回调地址
            request.setReturnUrl(alipayConfig.getReturnUrl());
            // 对象形式
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(payment.getTransactionId());
            model.setTotalAmount(payment.getPayerTotal().setScale(2, RoundingMode.UP).toString());
            model.setSubject(payment.getContent());
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            model.setTimeoutExpress(PaymentConstant.PAYMENT_TIMEOUT_LENGTH);
            // 商品明细信息，按需传入（多个商品）
            if (orders.getItems()!=null){
                List<GoodsDetail> goodsDetails = new ArrayList<>();
                for (OrderItemDTO order : orders.getItems()) {
                    GoodsDetail detail = new GoodsDetail();
                    detail.setGoodsId(order.getSkuId().toString());
                    detail.setGoodsName(order.getSkuName());
                    detail.setQuantity(order.getSkuQuantity().longValue());
                    detail.setPrice(order.getSkuPrice().setScale(2, RoundingMode.UP).toString());
                    goodsDetails.add(detail);
                }
                model.setGoodsDetail(goodsDetails);
            }
            //
            request.setBizModel(model);
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if(response.isSuccess()){
                log.info("调用成功，返回订单信息 ===>"+response.getBody());
            } else {
                log.info("调用失败，失败状态码 ===>"+ response.getCode()+",失败信息===>"+response.getMsg());
                throw new RuntimeException("调用支付信息失败");
            }
            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("创建支付信息异常");
        }
    }

}
